// @charset "utf-8";

define(function(require, exports, module) {
	var publicMethod = require('../../public/public'),
		clientApi = require('../../public/clientapi');

	var IndexBase  = require('../allindex/indexbase');

	function RzrqModule () {
		this.domId = 'rzrq';
		this.MODULENAME = '融资融券';
		this.EXPLAINTEXT = '';

		this.type = 'min';

		// this.code = '883900,1A0001';
		// this.indexCode = '883900';
		this.hcType = 'rzrqpjhc';

		this.latestVal1 = '--';
		this.latestVal2 = '--';

		this.beginDate = '';

		this.HighchartsObj = null;
		this.renderDom();
	}

	publicMethod.extendClass(RzrqModule, IndexBase);

	RzrqModule.prototype.renderDom = function () {
		var self = this;
		var htmlDom = '<li data-mname="'+ self.domId +'">' +
					'<div class="module-item">' +
						'<div class="module-header">' +
							'<a href="###" class="icon module-close-btn"></a>' +
							'<div class="date-wrap">' +
								// '<p class="date-wrap-single">' +
								// 	'<input type="text" class="icon date-picker" value="2017-02-16" id="'+ self.domId + 'DatePicker" />' +
								// 	'<a href="###" class="icon interval-btn" title="切换区间" id="'+ self.domId + 'IntervalBtn"></a>' +
								// '</p>' +
								'<p class="date-wrap-interval">' +
									'<input type="text" class="icon date-picker" value="2017-02-16" id="'+ self.domId + 'SDatePicker" />' +
									'<i class="separator">-</i>' +
									'<input type="text" class="icon date-picker" value="2017-02-16" id="'+ self.domId + 'EDatePicker"  />' +
									// '<a href="###" class="icon single-btn" title="切换区间" id="'+ self.domId + 'SingleBtn"></a>' +
								'</p>' +
							'</div>' +
							'<p class="module-name">'+ self.MODULENAME +'</p><i class="icon module-tip-btn" id="'+ self.domId +'ExplainBtn"><b class="icon"></b></i>' +
						'</div>' +
						'<div class="module-main">' +
							'<div class="chart-box" id="'+ self.domId +'ChartBox">' +
							'</div>' +
							'<div class="explain-box hide" id="'+ self.domId +'ExplainBox">' +
								'<p class="explain-text">'+ self.EXPLAINTEXT +'</p>' +
								'<div class="clearfix">' +
								'<div class="explain-left '+ self.domId +'-explain-pic">' +
								'</div>' +
								'<div class="explain-right">' +
									'<p>今日解读：<span id="'+ self.domId +'ExplainData">放量净流入12亿</span></p>' +
									'<br/>' +
									'<p>上涨概率回测</p>' +
									'<p id="'+ self.hcType +'HcData">历史数据回测中...</p>' +
								'</div>' +
								'</div>' +
							'</div>' +
							'<p class="non-trade-tip" id="'+ self.domId +'NonTradeTip">非交易日，请重新选择</p>' +
						'</div>' +
					'</div>' +
				'</li>';
				$('#modules-list-ul').append(htmlDom);
				self.renderData();

				self.bindEvents();
	}
	RzrqModule.prototype.renderData = async function() {
		var self = this;
		var preMonthDate = await clientApi.preMonthDate();
		var tradeDay = await clientApi.getTradingDay();

		$('#' + self.domId + 'SDatePicker').val(publicMethod.dateSplit(preMonthDate));
		$('#' + self.domId + 'EDatePicker').val(publicMethod.dateSplit(tradeDay));

		this.requestData(preMonthDate, tradeDay);

	}
	RzrqModule.prototype.requestData = function(startdate, enddate) {
		var self = this;

		var url = 'zx/get_homepage_data.lua?op=rzyebd&begin_date=' + startdate + '&end_date=' + enddate;
		var bool = clientApi.thsQuote.requestZxData({
			url: url,
			onready: function(res) {
				res = JSON.parse(res);
				self.analyticalData(res);
			}
		});
		if (!bool) {
			self.analyticalData([]);
		}

	}
	RzrqModule.prototype.getExplainData = async function(enddate) {
		var hour = await clientApi.serverHour();

		if (hour > 0945) {
			this.requestZxData(this.hcType, enddate);
		} else {
			this.renderRisingProb(this.hcType, '');
		}
	}
	RzrqModule.prototype.bindEvents = function(begin, end) {
		var self = this;

		var minDate = '2014-01-04';

		this.datePicker('', this.domId, function(date) {

		}, function(sdate, edate) {
			self.requestData(sdate, edate);
		}, minDate);

		var hoverTimer;
		$('#' + self.domId + 'ExplainBtn').hover(function() {
			var _this = this;
			hoverTimer = setTimeout(function() {
				$(_this).find('b').show();
				$(_this).parents('.module-item').find('.explain-box').show();
			}, 1000)
		}, function() {
			clearTimeout(hoverTimer);
		});

		$('#' + self.domId + 'ExplainBox').mouseleave(function() {
			$(this).parents('.module-item').find('b.icon').hide();
			$(this).hide();
		});
	}
	RzrqModule.prototype.analyticalData = async function(result) {
		var self = this;
		var rzzs = [];
		var rzchb = [];
		var dateArr = [];
		var rzzsDealt = [];
		var rzchbDealt = [];

		var latestVal1 = [],
			latestVal2 = [];

		if (result.length > 0) {

			$.each(result, function(i, val) {
				dateArr.push(val['date']);
				rzzs.push(Number(val['rzzs']) * 100);
				rzchb.push(Number(val['rzchb']));

				if (val['rzzs'] >= 4 && val['rzzs'] <= 10) {
					rzzsDealt.push(4);
				} else if (val['rzzs'] > 10) {
					rzzsDealt.push(4.5);
				} else if (val['rzzs'] >= -5 && val['rzzs'] <= -2.5) {
					rzzsDealt.push(-2.5);
				} else if (val['rzzs'] < -5) {
					rzzsDealt.push(-3);
				} else {
					rzzsDealt.push(Number(val['rzzs']) * 100);
				}

				if (val['rzchb'] >= 1.25 && val['rzchb'] <= 1.5) {
					rzchbDealt.push(1.25);
				} else if (val['rzchb'] > 1.5) {
					rzchbDealt.push(1.3);
				} else if (val['rzchb'] >= 0.6 && val['rzchb'] <= 0.85) {
					rzchbDealt.push(0.85);
				} else if (val['rzchb'] < 0.6) {
					rzchbDealt.push(0.8);
				} else {
					rzchbDealt.push(Number(val['rzchb']));
				}

			});
			latestVal1 = rzzs[rzzs.length - 1];
			latestVal2 = rzchb[rzchb.length - 1];
		} else {
			$('#' + self.domId + 'ExplainBtn').hide();
		}
		this.getExplainData(dateArr[dateArr.length - 1]);
		self.renderExplain(latestVal1, latestVal2);
		await self.drawChart(dateArr, rzzsDealt, rzchbDealt, rzzs, rzchb);
	}

	RzrqModule.prototype.renderExplain = function(rzzs, rzchb) {
		var self = this;
		var gradeTxt = '--',
			gradePic = 10,
			gradeTxt1 = '目前两市融资余额相比前几日出现明显增长，表明场外资金入场积极性较高，在资金流入的惯性推动下，短期股指上行概率较大；投资者对市场短期走势可持乐观态度。',
			gradeTxt2 = '目前两市融资余额相比前几日变化不大，表明场外资金持观望态度，投资者对市场短期走势需保持一份耐心。',
			gradeTxt3 = '目前两市融资余额相比前几日出现明显萎缩，表明场内资金出逃意愿较强，在资金流出的惯性作用下，短期股指下行概率较大；投资者对市场短期走势宜持谨慎态度。',
			gradeTxt4 = '';
		rzzs = rzzs * 100;
		if ((rzzs >= 3 && rzchb >= 1) || (rzzs >= 0 && rzchb >= 1.2)) {
			gradeTxt = '乐观';
			gradePic = 1;
			gradeTxt4 = gradeTxt1;
		} else if ((rzzs < -1.5 && rzchb < 1) || (rzzs < 0 && rzchb < 0.95)) {
			gradeTxt = '谨慎';
			gradePic = 2;
			gradeTxt4 = gradeTxt3;
		} else {
			gradeTxt = '中性';
			gradePic = 3;
			gradeTxt4 = gradeTxt2;
		}

		$('#' + self.domId + 'ExplainBox').find('.explain-text').text(gradeTxt4);
		$('.' + self.domId + '-explain-pic').css('background-position', -177 * gradePic + 'px 0');
		$('#' + self.domId + 'ExplainData').text(self.MODULENAME + '表现' + gradeTxt);
	}

	RzrqModule.prototype.drawChart = function(dateArr, series1, series2, rzzs, rzchb) {
		var self = this;
		var chartOptions = {
			credits: {
				enabled: false
			},
			title: {
				text: ''
			},
			chart: {
				backgroundColor: null,
				style: {
					"fontFamily": "Arial, \"Microsoft yahei\", Verdana, Helvetica, sans-serif",
					"fontSize": "12px"
				},
				margin: [40, 30, 30, 50]
			},
			series: [{
				name: '近3日融资余额变动百分比',
				type: 'line',
				color: '#6EB4E5',
				marker: {
					enabled: false,
					states: {
						hover: {
							fillColor: '#6EB4E5',
							radius: 2,
							lineColor: 'rgba(255, 255, 255, 1)',
							lineWidthPlus: 0
						}
					}
				},
				data: series1,
				tooltip: {
					valueSuffix: '%'
				}
			}, {
				name: '每日融资偿还比',
				type: 'line',
				yAxis: 1,
				color: '#F86A4E',
				marker: {
					enabled: false,
					states: {
						hover: {
							fillColor: '#F86A4E',
							radius: 2,
							lineColor: 'rgba(255, 255, 255, 1)',
							lineWidthPlus: 0
						}
					}
				},
				data: series2
			}],
			plotOptions: {
				line: {
					lineWidth: 1,
					states: {
						hover: {
							lineWidthPlus: 0
						}
					}
				}
			},
			xAxis: {
				lineWidth: 1,
				tickLength: 4,
				lineColor: '#808080',
				tickColor: '#808080',
				tickInterval: dateArr.length - 1,
				title: {
					text: ''
				},
				categories: dateArr,
				gridLineWidth: 0,
				labels: {
					align: 'center',
					rotation: 0,
					style: {
						color: '#afafaf'
					}
				}
			},
			yAxis: [{
				title: {
					text: '余额增速',
					align: 'high',
					offset: 0,
					rotation: 0,
					y: -10,
					x: 10,
					style: {
						color: '#afafaf'
					}
				},
				lineWidth: 1,
				tickColor: '#808080',
				tickPosition: 'outside',
				gridLineWidth: 0,
				tickLength: 4,
				tickWidth: 1,
				showEmpty: true,
				allowDecimals: true,
				tickPositions: [-3.0, -1.5, 0, 1.5, 3.0, 4.5],
				tickInterval: 1.5,
				lineColor: '#808080',
				labels: {
					format: '{value}%',
					style: {
						color: '#afafaf'
					},
					x: -7
				},
				showFirstLabel: false,
				showLastLabel: false,
				plotBands: [{
					color: '#2e0909',
					from: 3,
					to: 4.5
				}, {
					color: '#002e00',
					from: -1.5,
					to: -3
				}]
			}, {
				title: {
					text: '偿还比',
					align: 'high',
					offset: 0,
					rotation: 0,
					y: -10,
					x: -6,
					style: {
						color: '#afafaf'
					}
				},
				tickColor: '#808080',
				tickPosition: 'outside',
				gridLineWidth: 0,
				tickLength: 4,
				tickWidth: 1,
				showEmpty: true,
				tickPositions: [0.8, 0.9, 1.0, 1.1, 1.2, 1.3],
				tickInterval: 0.1,
				opposite: true,
				allowDecimals: true,
				showFirstLabel: false,
				showLastLabel: false,
				lineColor: '#999',
				lineWidth: 1,
				labels: {
					format: '{value}',
					style: {
						color: '#afafaf'
					},
					x: 7
				}
			}],
			legend: {
				align: 'center',
				verticalAlign: 'top',
				floating: true,
				symbolHeight: 20,
				symbolWidth: 14,
				itemStyle: {
					color: '#dedede',
					fontFamily: 'Microsoft yahei',
					fontWeight: 'normal'
				},
				itemHoverStyle: {
					color: '#bbb'
				}
			},
			tooltip: {
				shared: true,
				backgroundColor: '#2e3339',
				borderColor: '#505458',
				shape: '',
				crosshairs: [{
					width: 1,
					color: '#afafaf'
				}],
				valueDecimals: 2,
				// valueSuffix: '%',
				style: {
					fontFamily: 'Microsoft yahei',
					color: '#fff'
				}
				// ,
				// formatter: function() {
				// 	var tip = '<b>' + this.x + '</b>';
				// 	$.each(this.points, function() {
				// 		if (this.series.name === '近3日融资余额变动百分比') {
				// 			tip += '<br/>' + this.series.name + ': ' + rzzs[this.point.index].toFixed(2) + '%';
				// 		} else if (this.series.name === '每日融资偿还比') {
				// 			tip += '<br/>' + this.series.name + ': ' + rzchb[this.point.index].toFixed(2);
				// 		}
				// 	});
				// 	return tip;
				// }
			}
		};
		$('#' + self.domId + 'ChartBox').highcharts(chartOptions);
		self.HighchartsObj = $('#' + self.domId + 'ChartBox').highcharts();
	}

	RzrqModule.prototype.updateSeries = function() {

	}

	module.exports = RzrqModule;
});